import React, { useState } from 'react';
import { Modal, Upload, Button, message } from 'antd';
import { LoadingOutlined, UploadOutlined } from '@ant-design/icons';
import { uploadBatchList } from 'admin/servers/servers';

/**
 * 批量导入弹窗props
 */
interface IProps {
  show: boolean; // 显示隐藏
  // 额外数据
  data: {
    /**机器人版本号 */
    versionId: any;
    /**意图：intent，问答：question */
    mode: 'intention' | 'question';
  };
  callback: (data?: any) => void; // 回调函数
}

/**
 * 批量导入弹窗
 */
const UploadBatchModal: React.FC<IProps> = (props: IProps) => {
  /**模板名称，对应中文汉字 */
  const modeName = {
    intention: '意图',
    question: '问答',
  };
  const { show, data, callback } = props;
  const { versionId, mode } = data;
  const [uploading, setUploading] = useState(false);
  const [uploadFile, setUploadFile] = useState<any>();

  /**
   * 上传前校验
   */
  function beforeUpload(file: any): boolean {
    const fileName = file.name.split('.');
    const type = file.type;
    const isExcel =
      (type && type.indexOf('excel') > -1) || fileName[fileName.length - 1] === 'xlsx';
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isExcel) {
      message.error('请上传excel文件（只支持xlsx格式）!');
      return false;
    }
    if (!isLt2M) {
      message.error('文件大小超过2M!');
      return false;
    }
    setUploadFile(file);
    return true;
  }
  /**
   * 执行上传
   */
  function handleUpload() {
    if (uploading) return false;
    setUploading(true);
    const formData = new FormData();
    formData.append('file', uploadFile);
    console.log('开始上传文件', uploadFile);
    uploadBatchList(mode, versionId, formData)
      .then(res => {
        setUploading(false);
        callback('ok');
      })
      .catch(error => {
        console.error(`系统异常: ${JSON.stringify(error)}`);
        setUploading(false);
        callback();
      });
  }

  return (
    <Modal title="批量导入" width={500} visible={show} footer={null} onCancel={callback}>
      <div className="upload-tips">
        导入规则说明：
        <div>
          1.请先下载模板再导入{modeName[mode]}，仅支持<span>xlsx格式</span>
          ，大小<span>2M以内</span>；
        </div>
        <div>
          2.一次导入数据最多为<span>100,000条</span>；
        </div>
        {mode === 'intention' && <div>3.模板中所有字段必填。</div>}
      </div>
      <Upload
        name="file"
        accept=".xlsx"
        showUploadList={false}
        multiple={false}
        beforeUpload={beforeUpload}
        customRequest={handleUpload}
        disabled={uploading}
      >
        <Button type="primary" icon={uploading ? <LoadingOutlined /> : <UploadOutlined />}>
          本地上传
        </Button>
      </Upload>
      <Button
        style={{ marginLeft: 10 }}
        type="link"
        href={`/webapp/${mode}List_template.xlsx`}
        download={`批量导入${modeName[mode]}模板.xlsx`}
      >
        点击下载导入模板
      </Button>
    </Modal>
  );
};
export default UploadBatchModal;
